package com.example.common.base;

import android.content.Context;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import com.example.common.utils.LocaleManager;
import com.example.common.utils.LogUtil;

public abstract class BaseActivity<T extends ViewDataBinding, V extends BaseViewModel> extends AppCompatActivity {
    
    protected T binding;
    protected V viewModel;
    
    @Override
    protected void attachBaseContext(Context newBase) {
        // 应用保存的语言设置
        Context context = LocaleManager.applySavedLanguage(newBase);
        super.attachBaseContext(context);
        LogUtil.d(getClass().getSimpleName(), "Language applied in attachBaseContext");
    }
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtil.d(getClass().getSimpleName(), "onCreate");
        
        binding = DataBindingUtil.setContentView(this, getLayoutId());
        binding.setLifecycleOwner(this);
        
        viewModel = createViewModel();
        
        initView();
        initData();
        initObserver();
    }
    
    /**
     * 创建ViewModel，子类可以重写此方法来自定义ViewModel创建逻辑
     */
    protected V createViewModel() {
        return new ViewModelProvider(this).get(getViewModelClass());
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtil.d(getClass().getSimpleName(), "onDestroy");
        if (binding != null) {
            binding.unbind();
        }
    }
    
    protected abstract int getLayoutId();
    
    protected abstract Class<V> getViewModelClass();
    
    protected abstract void initView();
    
    protected abstract void initData();
    
    protected abstract void initObserver();
    
    protected void showLoading() {
        LogUtil.d(getClass().getSimpleName(), "showLoading");
    }
    
    protected void hideLoading() {
        LogUtil.d(getClass().getSimpleName(), "hideLoading");
    }
    
    protected void showError(String error) {
        LogUtil.e(getClass().getSimpleName(), "Error: " + error);
    }
    
    protected void showEmpty() {
        LogUtil.d(getClass().getSimpleName(), "showEmpty");
    }
    
    /**
     * 获取当前语言显示名称
     */
    protected String getCurrentLanguageDisplayName() {
        return LocaleManager.getCurrentLanguageDisplayName(this);
    }
    
    /**
     * 检查是否是中文环境
     */
    protected boolean isChineseLocale() {
        return LocaleManager.isChineseLocale(this);
    }
    
    /**
     * 检查是否是英文环境
     */
    protected boolean isEnglishLocale() {
        return LocaleManager.isEnglishLocale(this);
    }
}